//
//  StatusListViewModel.swift
//  ShangHaiWeiBo
//
//  Created by 蔡杰 on 16/3/13.
//  Copyright © 2016年 蔡杰. All rights reserved.
//

import Foundation

class StatusListViewModel {
    
    lazy var statusList = [StatusViewModel]()
    
    func cencelDate(){
    
        statusList.removeAll()
    }
    
    func loadStatus(isPullup: Bool, finished: (isSuccessed: Bool) -> () ){
    
        
        
        
        // 下拉刷新索引 - 取数组第一项 id
        let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
        // 上拉刷新索引 - 去数组最后一项 id
        let max_id = !isPullup ? 0 : (statusList.last?.status.id ?? 0)
        
        // 加载微博数据
        AFNworkTools.sharedTools.loadStatus(since_id: since_id, max_id: max_id) { (result) -> () in
            
       
            
            // [String: AnyObject] => [[String: AnyObject]]
            guard let array = result?["statuses"] as? [[String: AnyObject]] else {
                print("您的网路不给力")
                finished(isSuccessed: false)
                return
            }
            
            // 遍历数组，字典转`模型`
            var arrayM = [StatusViewModel]()
            for dict in array {
                arrayM.append(StatusViewModel(status: Status.yy_modelWithJSON(dict)!))
            }
            
            
            
            // 如果是上拉刷新，将刷新的数组放在后面
            if max_id > 0 {
                self.statusList += arrayM
            } else {
                self.statusList = arrayM + self.statusList
            }
            finished(isSuccessed: true)
           
        }
        
    }
}